package org.sky.ajax;

import org.apache.struts2.ServletActionContext;
import org.sky.action.MyActionSupport;
import org.sky.model.Person;
import org.sky.service.PersonService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.Map;

@Component("personAjax")
@Scope("prototype")
public class PersonAjax extends MyActionSupport {
    private PersonService personService;
    private HttpServletRequest request = ServletActionContext.getRequest();
    private HttpServletResponse response = ServletActionContext.getResponse();
    @Override
    public String execute(){
        try {
            Map<String, Object> params = new LinkedHashMap<String, Object>();
            //1.取参数
            response.setContentType("text/html;charset=utf-8");
            String old = this.request.getParameter("name");
            String name = URLDecoder.decode(old, "UTF-8");
            params.put("userName",name);
            Person person = (Person) personService.findSpecialObject(Person.class, params);
            //2.检查参数是否有问题
            if(old == null || old.length() == 0){
                this.sendResponse("用户名不能为空");
            } else{
                //3.校验操作
                if(person!=null){
                    //4。和传统应用不同之处。这一步需要将用户感兴趣的数据返回给页面段，而不是将一个新的页面发送给用户
                    //写法没有变化，本质发生了改变
                    this.sendResponse("用户名[" + name + "]已经存在，请使用其他用户名");
                } else{
                    this.sendResponse("用户名[" + name + "]尚未存在，可以使用该用户名注册");
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return NONE;
    }

   @Resource(name = "personServiceImpl")
   public void setPersonService(PersonService personService) {
       this.personService = personService;
   }

}
